<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCardNo">
        <el-input
          v-model="queryParams.idCardNo"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除标志" prop="deleteFlag">
        <el-select v-model="queryParams.deleteFlag" placeholder="是否删除" @change="handleQuery">
          <el-option
            v-for="item in deleteFlagOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="添加人" prop="addBy">
        <el-input
          v-model="queryParams.addBy"
          placeholder="请输入添加人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="修改人" prop="modifyBy">
        <el-input
          v-model="queryParams.modifyBy"
          placeholder="请输入修改人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inspection:people:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inspection:people:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inspection:people:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inspection:people:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="peopleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键id" align="center" prop="id" width="150px"/>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="性别" align="center" prop="sex"/>
      <el-table-column label="年龄" align="center" prop="ageAndAgeUnit"/>
      <el-table-column label="手机号" align="center" prop="mobile" width="120px"/>
      <el-table-column label="身份证号" align="center" prop="desensitizedIdCardNo" width="150px"/>
      <el-table-column label="照片">
        <template v-slot:default="scope">
          <img :src="scope.row.photo" alt="用户图片" style="width: 60px; height: 60px;"
               @click="handleImagePreview(scope.row.photo)">
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <div class="button-group">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['inspection:people:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['inspection:people:remove']"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="薪资" align="center" prop="salary"/>
      <el-table-column label="薪资类型" align="center" prop="salaryTypeName"/>
      <el-table-column label="生日" align="center" prop="birthday" width="150px"/>
      <el-table-column label="添加时间" align="center" prop="addTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.addTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" prop="addBy"/>
      <el-table-column label="修改时间" align="center" prop="modifyTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy"/>
    </el-table>
    <!-- 图片预览弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="previewImageUrl" alt="预览图片" style="width: 100%; max-width: 800px;">
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
    </span>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" @blur="checkMobile"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="item in sexOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNo">
          <el-input v-model="form.idCardNo" placeholder="请输入身份证号" @blur="idCardNoBlur"/>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择生日"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <div class="flex-container">
            <el-input-number
              v-model="form.age"
              controls-position="right"
              :min="1"
              :max="300"
              class="flex-item-input"
            ></el-input-number>
            <el-select
              v-model="form.ageUnit"
              placeholder="请选择年龄类型"
              class="flex-item-select"
            >
              <el-option
                v-for="item in ageUnitOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="薪资类型" prop="sex">
          <el-select v-model="form.salaryType" placeholder="请选择薪资类型">
            <el-option
              v-for="item in salaryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <template>
            <el-input-number v-model="form.salary" :precision="2" :step="0.1" :max="15000"></el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="照片" prop="photo">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8088/qiNiuYun/upload"
            :show-file-list="false"
            :on-success="uploadOk"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.flex-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.flex-item-input {
  flex: 1; /* 占据 2/3 的空间 */
}

.flex-item-select {
  flex: 2; /* 占据 1/3 的空间 */
  margin-left: 10px; /* 可选，用于添加一些间距 */
}

.button-group {
  display: flex; /* 使用Flexbox让按钮在同一行 */
  align-items: center; /* 垂直居中对齐（如果需要） */
  margin-left: 30px;
  /* justify-content: space-between; /* 按钮之间的间距（如果需要） */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
import {listPeople, getPeople, delPeople, addPeople, updatePeople, upload} from "@/api/inspection/people";
import {DatePicker} from 'element-ui';

export default {
  name: "People",
  components: {
    'el-date-picker': DatePicker
  },
  data() {
    return {
      previewImageUrl: null,
      sexOptions: [{
        value: "男",
        label: "男"
      }, {
        value: "女",
        label: "女"
      }],
      salaryOptions: [{
        value: 0,
        label: "年薪"
      }, {
        value: 1,
        label: "月薪"
      }, {
        value: 2,
        label: "日薪"
      }],
      ageUnitOptions: [{
        value: "岁",
        label: "岁"
      }, {
        value: "月",
        label: "月"
      }, {
        value: "天",
        label: "天"
      }],
      deleteFlagOptions: [{
        value: 0,
        label: "未删除"
      }, {
        value: 1,
        label: "已删除"
      }],
      dialogVisible: null,
      dialogImageUrl: null,
      imageUrl: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员表格数据
      peopleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sex: null,
        age: null,
        ageUnit: null,
        birthday: null,
        idCardNo: null,
        salary: null,
        salaryType: null,
        photo: null,
        deleteFlag: null,
        addTime: null,
        addBy: null,
        modifyTime: null,
        modifyBy: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkMobile() {
      console.log("走到校验里了，value为" + this.form.mobile);
      // 这里我们使用一个简单的正则表达式来校验手机号，但请注意，这只是一个基本示例
      // 在实际应用中，你可能需要根据你的具体需求来调整这个正则表达式
      const regex = /^1[3-9]\d{9}$/;
      if (!regex.test(this.form.mobile)) {
        this.$message.error('手机号格式不正确');
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 脱敏身份证号的方法
    desensitizeIdCard(idCard) {
      if (!idCard || idCard.length < 11) {
        return ''; // 如果身份证号长度不足11位，返回空字符串
      }
      // 保留前4位和后4位，中间部分用星号替换
      // 注意：这里假设身份证号是18位，如果是15位，需要调整逻辑
      const start = 2;
      const end = idCard.length - 2;
      const desensitized = idCard.slice(0, start) + '**************'.slice(0, end - start) + idCard.slice(end);
      return desensitized;
    },
    handleImagePreview(url) {
      this.previewImageUrl = url;
      this.dialogVisible = true;
    },
    // 计算年龄
    calculateAge(birthdayStr) {
      if (birthdayStr) {
        const birthday = new Date(`${birthdayStr.slice(0, 4)}-${birthdayStr.slice(4, 6)}-${birthdayStr.slice(6, 8)}`);
        const today = new Date();
        let age = today.getFullYear() - birthday.getFullYear();
        const m = today.getMonth() - birthday.getMonth();
        const d = today.getDay() - birthday.getDay();
        if (m < 0 || (m === 0 && today.getDate() < birthday.getDate())) {
          age--;
        }
        this.form.age = age;
        if (age < 1 && m >= 1) {
          this.form.ageUnit = "月";
        } else if (age < 1 && m < 1 && d > 0) {
          this.form.ageUnit = "天";
        } else {
          this.form.ageUnit = "岁";
        }
      } else {
        this.form.age = '';
      }
    },
    // 简单的身份证校验，只检查长度和可能的格式
    checkIdCardNumber(idCardNo) {
      const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
      if (idCardNo.length === 15) {
        // 15位旧身份证号简单校验，这里只检查长度
        return idCardNo.length === 15;
      } else if (idCardNo.length === 18) {
        // 18位新身份证号校验
        return idCardRegex.test(idCardNo);
      }
      return false;
    },
    idCardNoBlur() {
      const checkIdCardNoFlag = this.checkIdCardNumber(this.form.idCardNo);
      if (!checkIdCardNoFlag) {
        this.$message.error('身份证号格式错误');
      } else {
        // 提取生日部分（第7位到第14位）
        const birthStr = this.form.idCardNo.substring(6, 14);
        // 格式化生日为YYYY-MM-dd
        this.form.birthday = `${birthStr.slice(0, 4)}-${birthStr.slice(4, 6)}-${birthStr.slice(6, 8)}`;
        this.calculateAge(birthStr);
      }
    },
    uploadOk(response, file, fileList) {
      this.imageUrl = response.data;
      this.form.photo = response.data;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 查询人员列表 */
    getList() {
      console.log("走到这里了")
      this.loading = true;
      listPeople(this.queryParams).then(response => {
        this.peopleList = response.rows;
        this.peopleList.forEach(item => {
          if (item.salaryType == 0) {
            item.salaryTypeName = "年薪";
          } else if (item.salaryType == 1) {
            item.salaryTypeName = "月薪";
          } else if (item.salaryType == 2) {
            item.salaryTypeName = "日薪";
          }
          item.desensitizedIdCardNo = this.desensitizeIdCard(item.idCardNo)
          item.ageAndAgeUnit = item.age + item.ageUnit;
        })

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sex: null,
        age: null,
        mobile: null,
        ageUnit: null,
        birthday: null,
        idCardNo: null,
        salary: null,
        salaryType: null,
        photo: null,
        deleteFlag: null,
        addTime: null,
        addBy: null,
        modifyTime: null,
        modifyBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员";
      this.imageUrl = '';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPeople(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改人员";
        this.imageUrl = response.data.photo;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePeople(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPeople(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除人员编号为"' + ids + '"的数据项？').then(function () {
        return delPeople(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inspection/people/export', {
        ...this.queryParams
      }, `people_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
